<template>
  <div class="progress">
    <!-- 标题 -->
    <div class="progress-title items-center">
      <!-- 最后一位下注者获胜 -->
      <div class="progress-title-left" style="color: #ffb800">
        Hash PK {{ $t("common.start") }}
      </div>
      <div class="progress-title-right">Hash PK {{ $t("common.end") }}</div>
    </div>
    <!-- 中间进度条 -->
    <div class="items-center">
      <!-- 第一阶段进度条 -->
      <div
        v-if="false"
        class="first"
        :class="{ 'first-width': lottery.pkEndTime }"
      >
        <!-- 进度条 -->
        <div class="first-progress-bg">
          <div
            class="first-progress"
            :class="{
              'first-progress-animation': status != 1 && status != 3,
            }"
            :style="{ width: `${(curTimeFirst / totalTime) * 100}%` }"
          ></div>
          <img
            v-if="Number(Number(curTimeFirst) / totalTime) < 1"
            class="first-timeicon"
            src="/image/lotterymoney/progress-time2-icon.png"
          />
        </div>
        <!-- 开始时间 -->
        <div class="first-start items-center">
          <div class="first-start-point"></div>
          <div>
            {{ useDateFormat(Number(lottery.beginTime), "HH:mm").value }}
          </div>
          <div class="first-gtm" v-if="beginTimeTag != 0">
            {{ beginTimeTag }}
          </div>
          <!-- 提示信息 -->
          <van-popover
            class="popoverProgress"
            :offset="[0, 10]"
            placement="right"
          >
            <div class="popoverProgress-alert">
              {{
                $t(curDay == 7 ? "lotteryMoney.cjdyj" : "lotteryMoney.xydyj")
              }},{{
                $t("lotteryMoney.dyjsqxs")
                  .replace("xx:xx", startUTCFormat)
                  .replace("--:--", endUTCFormat)
              }}
            </div>
            <template #reference>
              <img
                class="popoverProgress-progressimg"
                :class="{
                  'popoverProgress-progressimg-spec': beginTimeTag != 0,
                }"
                src="/image/wh3-icon.svg"
              />
            </template>
          </van-popover>
        </div>
        <!-- 结束时间 -->
        <div class="first-end items-center">
          <div class="first-end-point"></div>
          <div>
            {{
              useDateFormat(Number(props.lottery.firstStageEndTime), "HH:mm")
                .value
            }}
          </div>
          <span
            class="first-gtm first-gtm-right"
            v-if="firstStageEndTimeTag != 0"
            >{{ firstStageEndTimeTag }}</span
          >
        </div>
      </div>
      <!-- 第二阶段 哈希 PK 进度条 -->
      <div class="hxpk" v-if="lottery.pkEndTime">
        <!-- 开始时间 -->
        <div class="hxpk-start items-center">
          <div class="hxpk-start-point"></div>
          <div class="hxpk-start-text">
            {{
              useDateFormat(Number(props.lottery.firstStageEndTime), "HH:mm")
                .value
            }}
          </div>
          <span class="hxpk-start-gtm" v-if="firstStageEndTimeTag != 0">{{
            firstStageEndTimeTag
          }}</span>
          <!-- 提示信息 -->
          <van-popover
            class="popoverProgress"
            :offset="[0, 10]"
            placement="right"
          >
            <div class="popoverProgress-alert">
              {{
                $t(curDay == 7 ? "lotteryMoney.cjdyj" : "lotteryMoney.xydyj")
              }},{{
                $t("lotteryMoney.dyjsqxs")
                  .replace("xx:xx", startUTCFormat)
                  .replace("--:--", endUTCFormat)
              }}
            </div>
            <template #reference>
              <img
                class="popoverProgress-progressimg"
                :class="{
                  'popoverProgress-progressimg-spec': beginTimeTag != 0,
                }"
                src="/image/wh3-icon.svg"
              />
            </template>
          </van-popover>
        </div>
        <!-- 进度条 -->
        <div class="hxpk-progress-bg">
          <!-- width: `${(curTimeSecond / lasThalfHour) * 100}%`, -->
          <div
            class="hxpk-progress"
            :class="{
              'hxpk-progress-animation':
                status != 1 && status != 3 && Number(secondProgressStyle) != 0,
            }"
            
            :style="{
              width: `${(0 / lasThalfHour) * 100}%`,
              opacity: Number(secondProgressStyle) != 0 ? 1 : 0,
            }"
          ></div>

          <img
            class="hxpk-timeicon"
            src="/image/lotterymoney/progress-time1-icon.png"
          />
        </div>
        <!-- 第二阶段:结束时间 -->
        <div class="hxpk-end">
          <div class="hxpk-end-point"></div>
          <div class="hxpk-end-text">
            {{ useDateFormat(pkEndTime, "HH:mm").value }}
            <span v-if="secondEndTimeTag != 0" class="hxpk-end-gtm">{{
              secondEndTimeTag
            }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup name="progress">
import { useDateFormat, useEventBus } from "@vueuse/core";
import { formatToTimeZone } from "@/utils/format";
import { usePageVisibility, useWindowSize } from "@vant/use";

const { width } = process.client ? useWindowSize() : { width: ref(375) };
const props = defineProps<{
  lottery: Object;
  status: Number;
  curDay?: Number;
  beginTimeTag?: String | Number;
  firstStageEndTimeTag?: String | Number;
  secondEndTimeTag?: String | Number;
}>();

const { t } = useI18n();

// 页面属性
const pageData = reactive({
  activitytStatus: 0, //   1 未开始  2 进行中  3 已结束
  serverTime: 0, // 默认当前时间
});

let unsubscribe: any = null; // 定时器通知对象
let unsubscribeFns: any = {}; // 执行的函数数组
const moneyInterval = useEventBus("lottery-money-interval-emit");

// 获取当天早上 xx 点的时间戳
const getTodayMorningTimestamp = (date, hour = 0, min = 0, se = 0, ms = 0) => {
  // 获取当前日期
  const now = date || new Date();
  // 创建一个新的 Date 对象，设置为当天的早上 10 点
  const todayMorning = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate(),
    hour,
    min,
    se,
    ms
  );
  // 获取时间戳
  return todayMorning.getTime();
};

// 第一阶段时间进度
const curTimeFirst = ref(0);
// 第一阶段总时间
const totalTime = computed(() => {
  if (props.lottery.beginTime) {
    return (
      Number(props.lottery.firstStageEndTime) - Number(props.lottery.beginTime)
    );
  }
  return 60 * 11.5 * 60 * 1000;
});

const firstProgressStyle = computed(() => {
  if (
    curTimeFirst.value == 0 ||
    Number(curTimeFirst.value) / totalTime.value < 0.05
  ) {
    return `0`;
  }

  return `calc(${(Number(curTimeFirst.value) / totalTime.value) * 100}% - ${
    width.value * 0.0438
  }px)`;
});

// 第二阶段时间进度
const curTimeSecond = ref(0);
// 第二阶段总时间(毫秒)
const lasThalfHour = computed(() => {
  if (props.lottery.pkEndTime) {
    return (
      Number(props.lottery.pkEndTime) - Number(props.lottery.firstStageEndTime)
    );
  }
  return Number(curTimeSecond.value) + 1000;
});

const secondProgressStyle = computed(() => {
  if (
    curTimeSecond.value == 0 ||
    Number(curTimeSecond.value) / lasThalfHour.value < 0.05
  ) {
    return `0`;
  }

  return `calc(${(Number(curTimeSecond.value) / lasThalfHour.value) * 100}% - ${
    width.value * 0.0438
  }px)`;
});

// 开始时间
const beginTime = computed(() => {
  return (
    Number(props.lottery.beginTime) ||
    getTodayMorningTimestamp(new Date(pageData.serverTime), 10)
  );
});
// 第一阶段结束时间
const firstStageEndTime = computed(() => {
  return (
    Number(props.lottery.firstStageEndTime) ||
    getTodayMorningTimestamp(new Date(pageData.serverTime), 21, 30)
  );
});
// 第二阶段-结束时间
const pkEndTime = computed(() => {
  return Number(props.lottery.pkEndTime);
});

// 活动开始时间转换成 GTM+7
let startUTCFormat = computed(() => {
  if (beginTime.value) {
    const { time } = formatToTimeZone(
      new Date(Number(beginTime.value)),
      "UTC",
      ""
    );
    return time.substring(0, 5);
  } else {
    return "10:00";
  }
});

let endUTCFormat = computed(() => {
  if (props.lottery.pkEndTime) {
    const { time } = formatToTimeZone(
      new Date(Number(pkEndTime.value)),
      "UTC",
      ""
    );
    return time.substring(0, 5);
  } else if (firstStageEndTime.value) {
    const { time } = formatToTimeZone(
      new Date(Number(firstStageEndTime.value)),
      "UTC",
      ""
    );
    return time.substring(0, 5);
  } else {
    return "22:00";
  }
});

const uodateProgress = () => {
  curTimeFirst.value = 0;
  curTimeSecond.value = 0;
  // 1. 使用服务器时间(准确)
  const now = pageData.serverTime ? new Date(pageData.serverTime) : new Date();
  let nowGtm7 = now.getTime();

  // 2. 计算比例
  const timeDifferenceFn = () => {
    if (nowGtm7 < beginTime.value) {
      curTimeFirst.value = 0;
      curTimeSecond.value = 0;
    } else if (
      nowGtm7 >= beginTime.value &&
      nowGtm7 <= firstStageEndTime.value
    ) {
      curTimeFirst.value = nowGtm7 - Number(beginTime.value);
      curTimeSecond.value = 0;
    } else if (
      nowGtm7 >= firstStageEndTime.value &&
      nowGtm7 <= pkEndTime.value
    ) {
      curTimeFirst.value = totalTime.value;
      setTimeout(() => {
        curTimeSecond.value = nowGtm7 - firstStageEndTime.value;
      }, 300);
    } else {
      curTimeFirst.value = totalTime.value;
      setTimeout(() => {
        curTimeSecond.value = pkEndTime.value - firstStageEndTime.value;
      }, 300);
    }
  };

  // 3.先计算一次进度
  timeDifferenceFn();

  // 4. 定时器计算进度
  unsubscribeFns["uodateProgress"] = (val) => {
    nowGtm7 += 1000;
    // 1.1 每隔 3 秒 更新一次进度
    if (val % 3000 > 2000 || val % 3000 == 0) {
      // console.log("progress-定时器", val);
      timeDifferenceFn();
    }
  };
};

// 活动时间变化,重新计算进度
const beginTimeWatch = watch(
  () => props.lottery.beginTime,
  (newVal, oldVal) => {
    // 1. 更新进度
    if (newVal && newVal != oldVal) {
      // console.log(newVal, "-活动时间变化,重新计算进度- ");
      uodateProgress();
    }
  }
);

// 服务器时间第一次变更,初始化逻辑
const serverTimeWatch = watch(
  () => pageData.serverTime,
  (newVal, oldVal) => {
    // console.log(newVal, "-服务器时间变更,初始化逻辑- ", oldVal);
    // 1. 更新进度
    if (newVal != oldVal && oldVal === 0) {
      uodateProgress();
    }
  }
);

// 进入后台不知道,啥情况,进度条不走了,日子也正常打印了,就是进度不走,只能在初始化一下数据
const pageVisibility = usePageVisibility();
const stopWatch = watch(pageVisibility, (value) => {
  // console.log("从后台进入前台: 刷新数据 ", value);
  if (value == "visible") {
    uodateProgress();
  }
});

// 页面属性
onMounted(() => {
  if (!unsubscribe) {
    unsubscribe = moneyInterval.on((val) => {
      // 1. 赋值
      pageData.serverTime = val;
      // 2. 更新进度
      // console.log("--进度更新--", Object.keys(unsubscribeFns).length);
      if (unsubscribeFns && Object.keys(unsubscribeFns).length > 0) {
        Object.keys(unsubscribeFns).forEach((key) => {
          // console.log("--unsubscribeFns--", key);
          const fn = unsubscribeFns[key];
          if (fn && typeof fn === "function") {
            fn(val);
          }
        });
      }
    });
  }
});

onBeforeUnmount(() => {
  // 1.注销通知
  if (unsubscribe) unsubscribe();
  beginTimeWatch && beginTimeWatch();
  serverTimeWatch && serverTimeWatch();
  stopWatch && stopWatch();
});
</script>
<style lang="scss" scoped>
.progress {
  position: relative;

  &-title {
    justify-content: space-between;
    margin-bottom: 13 * 2px;
    &-left {
      color: #007bff;
      font-size: 13 * 2px;
      font-weight: 590;
    }
    &-right {
      color: #ffb800;
      font-size: 13 * 2px;
      font-weight: 590;
    }
  }
  .hxpk {
    position: absolute;
    right: 0;
    // width: 102 * 2px;
    width: 100%;

    &-progress {
      @keyframes l1 {
        0% {
          background-position: 300%;
        }
        100% {
          background-position: 0%;
        }
      }
      &-bg {
        background-color: #e6edfe;
        // border-radius: 0 100px 100px 0;
        border-radius: 100px;
        overflow: hidden;
      }
      border-radius: 0 100px 100px 0;
      overflow: hidden;
      width: 100%;
      height: 20px;
      padding-left: 6px;
      background: linear-gradient(90deg, #ff6b00, #ff9200, #fff500, #ff6b00);
      background-size: 300% 100%;
      filter: blur(0.5px);
      &-animation {
        animation: l1 5s infinite linear;
      }
    }

    &-start {
      position: absolute;
      z-index: 9;
      top: 17 * 2px;
      left: 0 * 2px;
      &-point {
        position: absolute;
        z-index: 9;
        top: -30px;
        left: 0;
        width: 6 * 2px;
        height: 6 * 2px;
        background-color: #fff;
        border: 0.8px solid #002853;
        border-radius: 100px;
      }
      &-text {
        text-align: center;
        color: #999da7;
        font-size: 11 * 2px;
      }
      &-gtm {
        position: absolute;
        top: -6px;
        right: -8 * 2px;
        font-size: 8 * 2px;
        color: #999da7;
        font-weight: 400;
      }
    }

    &-end {
      position: absolute;
      z-index: 9;
      top: 17 * 2px;
      right: 0 * 2px;
      &-point {
        position: absolute;
        z-index: 9;
        top: -30px;
        right: 0;
        width: 6 * 2px;
        height: 6 * 2px;
        background-color: #fff;
        border: 0.8px solid #002853;
        border-radius: 100px;
      }
      &-text {
        text-align: center;
        color: #999da7;
        font-size: 11 * 2px;
      }
      &-gtm {
        position: absolute;
        top: -6px;
        right: -8 * 2px;
        font-size: 8 * 2px;
        color: #999da7;
        font-weight: 400;
      }
    }

    &-timeicon {
      position: absolute;
      z-index: 10;
      top: -15px;
      left: v-bind("secondProgressStyle");
      width: 18 * 2px;
      // height: 26 * 2px;
    }
  }

  .first {
    position: relative;
    z-index: 9;
    width: calc(100% - 18 * 2px - 6 * 2px);
    &-progress {
      @keyframes l2 {
        0% {
          background-position: 300%;
        }
        100% {
          background-position: 0%;
        }
      }
      &-bg {
        background-color: #e6edfe;
        border-radius: 100px;
        overflow: hidden;
      }
      border-radius: 100px;
      overflow: hidden;
      width: 100%;
      height: 20px;
      background: linear-gradient(90deg, #6eb5ff, #007dff, #00f0ff, #00b7ff);
      background-size: 300% 100%;
      filter: blur(0.5px);
      &-animation {
        animation: l2 5s infinite linear;
      }
    }
    &-width {
      width: calc(100% - 92 * 2px - 6 * 2px) !important;
    }
    &-start {
      position: absolute;
      z-index: 9;
      top: 16 * 2px;
      left: 0 * 2px;
      color: #999da7;
      font-weight: 400;
      font-size: 11 * 2px;
      &-point {
        position: absolute;
        z-index: 9;
        top: -28.5px;
        left: 0;
        width: 6 * 2px;
        height: 6 * 2px;
        background-color: #fff;
        border: 0.8px solid #002853;
        border-radius: 100px;
      }
    }
    &-gtm {
      position: absolute;
      top: -6px;
      right: 14 * 2px;
      font-size: 8 * 2px;
      color: #999da7;
      font-weight: 400;
      &-right {
        right: -8 * 2px;
      }
    }

    &-value {
      width: 100%;
      height: 22 * 2px;
      &-radius {
        border-radius: 3 * 2px 0 0 3 * 2px;
      }
    }
    &-text {
      position: absolute;
      z-index: 9;
      top: 5 * 2px;
      left: 50%;
      transform: translateX(-50%);
      color: #fff;
      font-weight: 900;
      font-size: 11 * 2px;
    }
    &-end {
      position: absolute;
      z-index: 9;
      top: 17 * 2px;
      color: #999da7;
      right: 0 * 2px;
      font-weight: 400;
      font-size: 11 * 2px;
      &-point {
        position: absolute;
        z-index: 9;
        top: -30px;
        right: 0;
        width: 6 * 2px;
        height: 6 * 2px;
        background-color: #fff;
        border: 0.8px solid #002853;
        border-radius: 100px;
      }
    }
    &-timeicon {
      position: absolute;
      z-index: 10;
      top: -15px;
      left: v-bind("firstProgressStyle");
      width: 18 * 2px;
      // height: 26 * 2px;
    }
  }
}

.popoverProgress {
  &-progressimg {
    width: 15 * 2px;
    height: 15 * 2px;
    margin-left: 4 * 2px;
    &-spec {
      margin-left: 8 * 2px;
    }
  }
  &-alert {
    max-width: 50vw;
    padding: 6 * 2px 12 * 2px;
    color: #fff;
    font-size: 11 * 2px;
    white-space: pre-wrap;
    background: rgba(10, 31, 106, 0.4) !important;
    backdrop-filter: blur(10px);
    border-radius: 6 * 2px;
    overflow: hidden;
  }
}
</style>
<style lang="scss">
.popoverProgress {
  .van-popover__content {
    background: transparent !important;
  }
  .van-popover__arrow {
    color: rgba(10, 31, 106, 0.4) !important;
  }
}
</style>
